package cn.bugstack.springframework.core.io;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @param
 * @author oyz
 * @version 1.0
 * @description: TODO
 * @date 2022/3/20 14:31
 */
public class ClassPathResource implements Resource{

    private final String path;

    private ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path,null);
    }


    public ClassPathResource(String path,ClassLoader classLoader) {
        Assert.notNull(path,"Path must be not null");
        this.path = path;
        this.classLoader = classLoader!=null ? classLoader : Thread.currentThread().getContextClassLoader();
    }


    /**
     * @description: TODO 用于通过 ClassLoader 读取 ClassPath 下的文件信息
     * @author oyz
     * @param null
     * @date 2022/3/20 14:42
     * @version 1.0
     */
    @Override
    public InputStream getInputStream() throws IOException {
        InputStream resourceAsStream = classLoader.getResourceAsStream(path);
        if (ObjectUtil.isNull(resourceAsStream)){
            throw new FileNotFoundException(this.path + " cannot be opened because it does not exist");
        }
        return resourceAsStream;
    }
}
